import React, { Component } from 'react';
import {
	Platform,
	BackHandler,
	ToastAndroid,
	Text,
	View,
	Image,
	StatusBar,
	PermissionsAndroid
} from 'react-native';
import { ENVIRONMENT } from '../config/env';
import { GLOBAL } from '../config/global';
import { STORAGE_CONSTANT } from '../config/storage';
import SplashScreen from 'react-native-splash-screen';
import Dictionary from '../utils/dictionary';
import ToastUtil from '../utils/toast';
import ExceptionHandler from '../utils/exceptionHandler';
import Permission from '../utils/permission';
import StorageHelper from '../utils/storageHelper';
import TouchID from 'react-native-touch-id';
import * as Keychain from 'react-native-keychain';


export class SplashPage extends Component {
	static Navigation_routers;
	static navigationOptions = {
		header: ({ navigation }) => {
			let { state: { routes } } = navigation;
			Navigation_routers = routes;//全局的路由
		}
	}

	constructor(props) {
		super(props);

		GLOBAL.ROOT_NAVIGATION = this.props.navigation;
	}

	componentWillMount () {
		if (Platform.OS === 'android') {
			BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
		}
	}

	async componentDidMount () {
		SplashScreen.hide();
		//应用异常处理
		ExceptionHandler.init();
		//安卓获取权限问题
		await this.requestLocationPermission();
		//获取缓存数据
		GLOBAL.TOKEN = await StorageHelper.get(STORAGE_CONSTANT.TOKEN) || null;
		GLOBAL.BIND_LOGIN_TYPE = await StorageHelper.get(STORAGE_CONSTANT.BIND_LOGIN_TYPE) || null;
		GLOBAL.BIND_GESTURE_PASSWORD = await StorageHelper.get(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD);
		if (ENVIRONMENT[GLOBAL.CURR_ENV].switchEnable) {
			let cache = await StorageHelper.get(STORAGE_CONSTANT.CURR_ENV);
			if (cache === 'ZHDS') {
				cache = 'PROD';
				await StorageHelper.set(STORAGE_CONSTANT.CURR_ENV, cache);
			}
			if (ENVIRONMENT[GLOBAL.CURR_ENV].isProduction && (cache !== 'PROD' || cache !== 'ZHDS')) cache = GLOBAL.CURR_ENV
			GLOBAL.CURR_ENV = cache || GLOBAL.CURR_ENV;
		}

		//初始化数据字典
		await Dictionary.init();
		//获取权限数据
		await Permission.init();
		GLOBAL.CURR_MODULE = '2.0';

		let bindBimetoryAuth = STORAGE_CONSTANT.BIND_BIOMETRY_AUTH ? await StorageHelper.get(STORAGE_CONSTANT.BIND_BIOMETRY_AUTH) : null;
		if(GLOBAL.BIND_LOGIN_TYPE==='GESTURE'){
			try {
				Keychain.getGenericPassword().then(credentials => {
					if (credentials && credentials.username && credentials.password) {
						console.log(credentials);
						this.props.navigation.navigate('gestureLogin', {
							autoLogin: true,
							...credentials
						})
					} else {
						console.log('No credentials stored');
						Keychain.resetGenericPassword()
						//TODO: 未绑定，必须重新登陆
						this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
					}
				})
			} catch (error) {
				console.log("Keychain couldn't be accessed!", error);
				this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
			}
			GLOBAL.BIND_BIOMETRY_AUTH = JSON.parse(bindBimetoryAuth);
			TouchID.isSupported({}).then(biometryType => {
				GLOBAL.SUPPORT_BIOMETRY_TYPE = biometryType;
			})
		}
		else{
			try {
				GLOBAL.BIND_BIOMETRY_AUTH = JSON.parse(bindBimetoryAuth);
				TouchID.isSupported({})
					.then(biometryType => {
						GLOBAL.SUPPORT_BIOMETRY_TYPE = biometryType;
						if (GLOBAL.BIND_BIOMETRY_AUTH) {
							try {
								Keychain.getGenericPassword().then(credentials => {
									if (credentials && credentials.username && credentials.password) {
										console.log(credentials);
										this.props.navigation.navigate(GLOBAL.TOKEN ? 'AuthenticationPages': 'LoginPage', {
											autoLogin: true,
											biometryType,
											...credentials
										})
									} else {
										console.log('No credentials stored');
										Keychain.resetGenericPassword()
										//TODO: 未绑定，必须重新登陆
										this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
									}
								})
							} catch (error) {
								console.log("Keychain couldn't be accessed!", error);
								this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
							}
						} else {
							this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
						}
					})
					.catch(error => {
						GLOBAL.SUPPORT_BIOMETRY_TYPE = null;
						console.log('biometry support error: ', error.code)
						this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
					});
			} catch (error) {
				this.props.navigation.navigate(GLOBAL.TOKEN ? 'Layout' : 'LoginPage')
			}
		}
		
	}

	async requestLocationPermission () {
		if (Platform.OS == 'ios') return true;
		try {
			const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, {
				title: '申请获取位置权限',
				message: '掌上化销需要获得设备所在位置信息'
			});
			return granted === PermissionsAndroid.RESULTS.GRANTED;
		} catch (err) {
			ToastUtil.showError(err);
			return false;
		}
	}

	onBackAndroid = () => {
		const len = Navigation_routers.length;
		if (Navigation_routers[len - 1].routeName === 'LoginPage' || Navigation_routers[len - 1].routeName === 'Layout') {
			if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
				//最近2秒内按过back键，可以退出应用。
				BackHandler.exitApp();
				return false;
			}
			this.lastBackPressed = Date.now();
			ToastAndroid.showWithGravity('再按一次退出应用', ToastAndroid.SHORT, ToastAndroid.CENTER);
			return true;
		}
		//强制修改密码，禁止返回上一页
		else if (Navigation_routers[len - 1].routeName === 'SetPassWordPage') {
			if (GLOBAL.pwdReset) {
				return true;
			}
		}
		return false;
	}

	componentWillUnmount () {
		if (Platform.OS === 'android') {
			BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
		}
	}

	render () {
		return (
			<View style={styles.container}>
				<StatusBar
					backgroundColor='#fff'
					barStyle="default"
				/>
				<Image source={require("../imgs/global/log.png")} style={styles.icon} />
				<Text style={styles.welcome}>欢迎来到掌上化销</Text>
			</View>
		)
	}
}

const styles = {
	container: {
		flex: 1,
		height: '100%',
		backgroundColor: '#fff',
		alignItems: 'center',
	},
	icon: {
		width: 115 * GLOBAL.SCALE,
		height: 115 * GLOBAL.SCALE,
		marginTop: 150 * GLOBAL.SCALE,
		marginBottom: 40 * GLOBAL.SCALE,
	},
	welcome: {
		fontSize: 18 * GLOBAL.SCALE,
	}
}
